<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>axios请求拦截器</title>
  <link href="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.css" rel="stylesheet">
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.js"></script>
</head>
<body>
<h1>axios请求拦截器</h1>

<button id="btn">点击查询数据</button>
<script>
  const btn = document.querySelector('#btn')
  const myAxios = axios.create({
    baseURL: '/',
    timeout: 10000,
    headers: {}
  })
  myAxios.interceptors.request.use(function (config) {
    // alert('我要开始请求数据了!')
    Nprogress.start()
    const token = 'sd1q321dq651.d1q56w13as21d.d15ew61f3wf156'
    // console.log(config)
    config.headers.common.token = token
    // console.log(config)
    return config
  }, function (error) {
    return Promise.reject(error)
  })
  // 添加响应拦截器
  myAxios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    Nprogress.done()
    if (response.data.code !== 10000) {
      return Promise.reject(response.data.msg)
    }

    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  })


  btn.onclick = async function () {
    const value = prompt('请输入你想要查询的ID')
    try {
      const re = await myAxios.get('/interceptor', {
        params: {
          userId: value
        }
      })
    } catch (e) {
      console.log('出现错误', e)
    }
  }
</script>
</body>
</html>